<template>
  <el-dialog v-model="visible" title="预览" width="50%" center>
    <div id="vue-pdf-view">
      <div class="pdf-controls">
        <div class="page-controls">
          <button @click="prevPage" :disabled="pageNum <= 1">上一页</button>
          <span>{{ pageNum }} / {{ numPages }}</span>
          <button @click="nextPage" :disabled="pageNum >= numPages">下一页</button>
        </div>
        <div class="zoom-controls">
          <button @click="zoomOut">缩小</button>
          <span>{{ Math.round(scale * 100) }}%</span>
          <button @click="zoomIn">放大</button>
        </div>
      </div>
      <div id="page-view" :style="{ transform: `scale(${scale})` }">
        <VuePdfEmbed
          v-if="pdfSource.url"
          :source="pdfSource"
          :page="pageNum"
          textLayer
          @rendered="onPageRendered"
          @loading="onLoading"
          @error="onError"
          @loaded="onLoaded"
        />
      </div>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-if="error" class="error">{{ error }}</div>
    </div>
  </el-dialog>
</template>

<script>
import VuePdfEmbed from 'vue-pdf-embed'
import * as pdfjsLib from 'pdfjs-dist'

// 设置PDF.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`

export default {
  components: { VuePdfEmbed },
  props: {
    centerDialogVisible: {
      type: Boolean,
      default: false
    },
    pdfUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      pdfSource: {
        url: '',
        cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.9.359/cmaps/',
        cMapPacked: true,
        httpHeaders: {
          'Access-Control-Allow-Origin': '*'
        },
        withCredentials: true
      },
      pageNum: 1,
      numPages: 1,
      scale: 1.0,
      loading: false,
      error: null
    }
  },
  computed: {
    visible: {
      get() {
        return this.centerDialogVisible
      },
      set(value) {
        this.$emit('update:centerDialogVisible', value)
      }
    }
  },
  watch: {
    pdfUrl: {
      immediate: true,
      async handler(newUrl) {
        if (newUrl) {
          try {
            this.loading = true
            // 先尝试直接加载URL
            this.pdfSource.url = newUrl
            
            // 如果URL是跨域的，可以尝试通过blob方式加载
            const response = await fetch(newUrl, {
              credentials: 'include' // 包含cookies
            })
            if (!response.ok) throw new Error('PDF加载失败')
            
            const blob = await response.blob()
            this.pdfSource.url = URL.createObjectURL(blob)
            
            this.loading = false
          } catch (err) {
            this.error = '加载PDF失败：' + err.message
            this.loading = false
          }
        }
      }
    }
  },
  methods: {
    prevPage() {
      if (this.pageNum > 1) {
        this.pageNum--
      }
    },
    nextPage() {
      if (this.pageNum < this.numPages) {
        this.pageNum++
      }
    },
    zoomIn() {
      this.scale = Math.min(this.scale + 0.1, 2.0)
    },
    zoomOut() {
      this.scale = Math.max(this.scale - 0.1, 0.5)
    },
    onPageRendered() {
      this.loading = false
      this.error = null
    },
    onLoading() {
      this.loading = true
      this.error = null
    },
    onError(error) {
      this.loading = false
      this.error = 'PDF加载失败：' + error
      console.error('PDF加载错误:', error)
    },
    onLoaded(pdf) {
      this.numPages = pdf.numPages
      this.loading = false
      this.error = null
    }
  },
  beforeUnmount() {
    // 清理blob URL
    if (this.pdfSource.url && this.pdfSource.url.startsWith('blob:')) {
      URL.revokeObjectURL(this.pdfSource.url)
    }
  }
}
</script>

<style scoped lang="scss">
#vue-pdf-view {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  overflow: auto;
}

.pdf-controls {
  position: sticky;
  top: 0;
  background: white;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  z-index: 100;

  .page-controls, .zoom-controls {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  button {
    padding: 5px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background: white;
    cursor: pointer;

    &:hover {
      background: #f5f5f5;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}

#page-view {
  transform-origin: top center;
  transition: transform 0.2s ease;
}

.loading, .error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  border-radius: 4px;
}

.loading {
  background: rgba(255,255,255,0.9);
}

.error {
  background: #ffebee;
  color: #c62828;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-thumb {
  border-radius: 15px;
  background-color: #eee;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #CBCBFF;
}
:deep(.el-dialog){
    --el-dialog-margin-top: 1vh !important;
}
</style>